using Zhaoxi.MSACommerce.PaymentService.Core.Entities;
using Zhaoxi.MSACommerce.PaymentService.Infrastructure.Data;
using Zhaoxi.MSACommerce.PaymentService.UserCases.Service;
using ZhaoXi.MSACommerce.SharedKenel.Messaging;
using ZhaoXi.MSACommerce.SharedKenel.Result;
using ZhaoXi.MSACommerce.UserCases.Common.Interfaces;

namespace Zhaoxi.MSACommerce.PaymentService.UserCases.Commands;

public record CreatePayLogCommand(long OrderId) : ICommand<Result<long>>;

public class CreatePayLogCommandHandler(PaymentDbContext dbContext,
    IOrderService orderService,
    IUser user) : ICommandHandler<CreatePayLogCommand, Result<long>>
{
    public async Task<Result<long>> Handle(CreatePayLogCommand request, CancellationToken cancellationToken)
    {
       var response = await orderService.GetOrderAsync(request.OrderId);
       
       if (!response.IsSuccessStatusCode) return Result.Failure("订单不存在");
       
       var order = response.Content!;
       
       var payLog = new PayLog(request.OrderId, order.ActualPay, (long)user.Id);
       
       dbContext.PayLogs.Add(payLog);
       
       await dbContext.SaveChangesAsync(cancellationToken);
       
       return Result.Success(payLog.Id);
    }
}
